{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "#@title Licensed under the Apache License, Version 2.0 (the \"License\"); { display-mode: \"form\" }\n",
    "# you may not use this file except in compliance with the License.\n",
    "# You may obtain a copy of the License at\n",
    "#\n",
    "# https://www.apache.org/licenses/LICENSE-2.0\n",
    "#\n",
    "# Unless required by applicable law or agreed to in writing, software\n",
    "# distributed under the License is distributed on an \"AS IS\" BASIS,\n",
    "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
    "# See the License for the specific language governing permissions and\n",
    "# limitations under the License."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Producing data for synthetic regression"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "The autoreload extension is already loaded. To reload it, use:\n",
      "  %reload_ext autoreload\n"
     ]
    }
   ],
   "source": [
    "import os\n",
    "import sys\n",
    "from jax import config\n",
    "import haiku as hk\n",
    "import jax\n",
    "from jax import numpy as jnp\n",
    "import numpy as onp\n",
    "import time\n",
    "import tqdm\n",
    "\n",
    "from bnn_hmc import data\n",
    "from bnn_hmc import models\n",
    "from bnn_hmc import nn_loss\n",
    "from bnn_hmc import train_utils\n",
    "from bnn_hmc import precision_utils\n",
    "from jax.experimental import optix\n",
    "import functools\n",
    "\n",
    "from matplotlib import pyplot as plt\n",
    "\n",
    "%matplotlib inline\n",
    "%load_ext autoreload\n",
    "%autoreload 2"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [],
   "source": [
    "tpu_ip = \"10.0.0.2\"\n",
    "config.FLAGS.jax_xla_backend = \"tpu_driver\"\n",
    "config.FLAGS.jax_backend_target = \"grpc://{}:8470\".format(tpu_ip)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [],
   "source": [
    "net_fn = models.make_mlp_regression(layer_dims=[100, 100, 100])\n",
    "net = hk.transform_with_state(net_fn)\n",
    "net_apply = net.apply\n",
    "net_apply = jax.default_matmul_precision(\"tensorfloat32\")(\n",
    "  net_apply)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "x = jnp.concatenate([jnp.linspace(a, b, 40) for a, b in zip([-10, 6, 14], [-6, 10, 18])])\n",
    "x_ = jnp.linspace(-14, 22, 120)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def featurize(x):\n",
    "    return jnp.concatenate([x[:, None], x[:, None]**2], axis=1)\n",
    "\n",
    "f = featurize(x)\n",
    "f_ = featurize(x_)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "params, net_state = net.init(jax.random.PRNGKey(0), (f, None), True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "std = 0.1\n",
    "normal_key = jax.random.PRNGKey(22)\n",
    "\n",
    "num_leaves = len(jax.tree_leaves(params))\n",
    "normal_keys = list(jax.random.split(normal_key, num_leaves))\n",
    "treedef = jax.tree_structure(params)\n",
    "normal_keys = jax.tree_unflatten(treedef, normal_keys)\n",
    "params = jax.tree_multimap(lambda p, key: jax.random.normal(key, p.shape) * std,\n",
    "                           params, normal_keys)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "noise_key = jax.random.PRNGKey(0)\n",
    "noise_std = 0.02\n",
    "\n",
    "y, _ = net_apply(params, net_state, None, (f, None), False)\n",
    "y_, _ = net_apply(params, net_state, None, (f_, None), False)\n",
    "y += jax.random.normal(noise_key, y.shape) * noise_std"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "plt.plot(x, y, \"bo\")\n",
    "plt.plot(x_, y_, \"-k\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "data = onp.savez(\n",
    "    \"synth_reg_data.npz\",\n",
    "    x_=onp.asarray(x_),\n",
    "    y_=onp.asarray(y_),\n",
    "    f_=onp.asarray(f_),\n",
    "    x=onp.asarray(x),\n",
    "    y=onp.asarray(y),\n",
    "    f=onp.asarray(f)\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "noise_var = \n",
    "\n",
    "log_prior_fn, log_prior_diff_fn = (\n",
    "    nn_loss.make_gaussian_log_prior(weight_decay=0.1))"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
